/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Modele;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author steven
 */
public class ModeleTableau extends AbstractTableModel {

    private final ArrayList<Port> ports = new ArrayList<Port>();
    private final String[] entetes = {"Numero", "Type"};

    public ModeleTableau() {
        super();
        chargerPorts();
    }

    @Override
    public int getRowCount() {
        return ports.size();
    }

    @Override
    public int getColumnCount() {
        return entetes.length;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return entetes[columnIndex];
    }
    
    public ArrayList<Port> getListPorts(){
        return ports;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return ports.get(rowIndex).getNumPort();
            case 1:
                return ports.get(rowIndex).getProtocole();
            default:
                return null; //Ne devrait jamais arriver
        }
    }

    public void addPort(Port port) {
        ports.add(port);
        fireTableRowsInserted(ports.size() - 1, ports.size() - 1);
    }

    public void removePort(int rowIndex) {
        ports.remove(rowIndex);

        fireTableRowsDeleted(rowIndex, rowIndex);
    }

    private void chargerPorts() {

        try {

            FileInputStream fichier = new FileInputStream("ports.ser");
            ObjectInputStream ois = new ObjectInputStream(fichier);
            
            int nbPorts = ois.readInt();
            
            for (int i = 0; i < nbPorts; i++){
                ports.add((Port) ois.readObject());
            }

        } catch (java.io.IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void enregistrerPorts() {

        try {

            FileOutputStream fichier = new FileOutputStream("ports.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fichier);

            oos.writeInt(ports.size());
            
            for (Port p : ports) {
                oos.writeObject(p);
            }

            oos.flush();
            oos.close();

        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }
}
